package com.gitee.cnlongs.cnlongmq.basic.config;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gitee.cnlongdb.basic.config.LongDbConfig;
import com.gitee.cnlongdb.basic.constant.LongDbConstant;
import com.gitee.cnlongdb.basic.utils.DealStrSubUtils;
import com.gitee.cnlongdb.basic.utils.FieldHandlerUtils;
import com.gitee.cnlongdb.basic.utils.RandomUtil;
import com.gitee.cnlongs.cnlongmq.basic.constant.CnLongMqConstant;
import com.gitee.cnlongs.cnlongmq.basic.entitiy.request.CnLongMqConfiger;
import com.gitee.cnlongs.cnlongmq.basic.entitiy.request.CnLongMessageQueue;
import com.gitee.cnlongs.cnlongmq.basic.enums.CnLongMqConfig;
import com.gitee.cnlongs.cnlongmq.basic.enums.CnLongMqStatus;

/**
 * 系统名称：LongmqConfigHandler.java
 * 模块名称：
 * 模块描述：中国龙[消息队列] - 配置文件解析器
 * 功能列表：
 * 模块作者：ZOUYONG
 * 开发时间：2019年3月31日 下午8:38:46
 * 模块路径：com.gitee.cnlongs.cnlongmq.basic.config.LongmqConfigHandler
 * 更新记录：
 */
public class LongmqConfigHandler {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(LongmqConfigHandler.class);

	/**
	 * 功能描述：获取cnlongmq-总配置信息
	 * 模块作者：ZOUYONG
	 * 开发时间：2019年4月1日 下午8:20:35
	 * 更新记录：
	 * 返回数据：CnLongMqConfigEntity
	 */
	public static CnLongMqConfiger getLongMqConfigInfo(File cfgFile) {
		CnLongMqConfiger config = new CnLongMqConfiger();
		// 获取总配置文件的内容
		BufferedReader bufReader = null;
		BufferedInputStream bis = null;
		try {
			// FileReader:用来读取字符文件的便捷类。
			bis = new BufferedInputStream(new FileInputStream(cfgFile));
			bufReader = new BufferedReader(
				new InputStreamReader(bis, LongDbConstant.longdbSystemCharset), 
				LongDbConfig.longdbTableFileBufferedReaderSize
			);
			String content = null;
			while ((content = bufReader.readLine()) != null) {
				if(StringUtils.isBlank(content) || content.startsWith(CnLongMqConstant.longmqSeparateC)) {
					continue;
				}
				String[] cfgAry = content.split(CnLongMqConstant.longmqSeparateB);
				if(cfgAry.length <= 1) {
					continue;
				}
				String cfgName = cfgAry[0];
				if(StringUtils.isBlank(cfgName)) {
					continue;
				}

				Field field = config.getClass().getDeclaredField(cfgAry[0]);
				Object value = cfgAry[1];
				if(cfgAry[0].equals(CnLongMqConfig.longMqTimeOut.name()) || cfgAry[0].equals(CnLongMqConfig.longMqPort.name())) {
					value = Integer.valueOf(value.toString());
				}
				FieldHandlerUtils.setObjectValue(field, config, value);
			}
		}
		catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
		finally {
			if (bufReader != null) {
				try {
					bufReader.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
					bufReader = null;
				}
			}
			if(null != bis) {
				try {
					bis.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
					bis = null;
				}
			}
		}
		return config;
	}

	/**
	 * 功能描述：获取cnlongmq-队列信息
	 * 模块作者：ZOUYONG
	 * 开发时间：2019年4月1日 下午8:26:29
	 * 更新记录：
	 * 返回数据：CnLongMqMessageEntity
	 */
	public static List<CnLongMessageQueue> getLongMqSeq(CnLongMqConfiger mqConfig, File seqFile) {
		List<CnLongMessageQueue> seqList = new ArrayList<CnLongMessageQueue>();
		// 获取总配置文件的内容
		BufferedReader bufReader = null;
		BufferedInputStream bis = null;
		try {
			// FileReader:用来读取字符文件的便捷类。
			bis = new BufferedInputStream(new FileInputStream(seqFile));
			bufReader = new BufferedReader(
				new InputStreamReader(bis, LongDbConstant.longdbSystemCharset), 
				LongDbConfig.longdbTableFileBufferedReaderSize
			);
			String rgex = "'(.*?)'";
			String content = null;
			while ((content = bufReader.readLine()) != null) {
				if(StringUtils.isBlank(content)) {
					continue;
				}
				String rule = DealStrSubUtils.getSubUtilSimple(content, rgex);
				if(StringUtils.isBlank(rule) || rule.startsWith(CnLongMqConstant.longmqSeparateC)) {
					continue;
				}
				CnLongMessageQueue seq = new CnLongMessageQueue(
						mqConfig.getLongMqName(), mqConfig.getLongMqIp(), mqConfig.getLongMqPort());
				seq.setId(RandomUtil.getCharAndNumr(24));
				seq.setStartActiveDate(new Date());
				seq.setLongMqStatus(CnLongMqStatus.active.name());
				String[] seqAry = rule.split(CnLongMqConstant.longmqSeparateA);
				for (String str : seqAry) {
					String[] cfgAry = str.split(CnLongMqConstant.longmqSeparateB);
					if(cfgAry.length <= 1) {
						continue;
					}
					Field field = seq.getClass().getDeclaredField(cfgAry[0]);
					Object value = cfgAry[1];
					if(cfgAry[0].equals(CnLongMqConfig.timeout.name())) {
						value = Integer.valueOf(value.toString());
					}
					FieldHandlerUtils.setObjectValue(field, seq, value);
				}
				seq.check(); // 校验对象必填属性是否有值
				seqList.add(seq);
			}
		}
		catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
		finally {
			if (bufReader != null) {
				try {
					bufReader.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
					bufReader = null;
				}
			}
			if(null != bis) {
				try {
					bis.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
					bis = null;
				}
			}
		}
		return seqList;
	}

}
